package com.zw.cloud.common.utils;

import com.google.common.collect.Lists;
import com.zw.cloud.common.exception.BizException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.security.*;
import java.util.Date;
import java.util.List;

@Slf4j
public class JwtRSAUtils {
    public static final String SECRET_KEY = "asdfgbvcx..ewq11..wef";
    public static void main(String[] args) throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom(SECRET_KEY.getBytes());
        keyPairGenerator.initialize(2048, secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        // 获取公钥并写出
        PublicKey publicKey = keyPair.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        String publicKeyStr = Base64.encodeBase64String(publicKeyBytes);
        log.info("publicKeyStr: " + publicKeyStr);
        log.info("===========================================================");

        // 获取私钥并写出
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        String privateKeyStr = Base64.encodeBase64String(privateKeyBytes);
        log.info("privateKeyStr: " + privateKeyStr);

        String jwt = createJwt("1601129911448313857","枫无痕", Lists.newArrayList("seller"),privateKey);
        System.out.println(jwt);
        Claims claims = parseJwt(jwt, publicKey);
        System.out.println(claims.getId());
    }

    public static String createJwt(String userId, String username, List<String> roleList,PrivateKey privateKey) {
        long now = System.currentTimeMillis();//当前时间
        long exp = now + 1000 * 60 * 30;//过期时间为30分钟
        JwtBuilder builder = Jwts.builder().setId(userId)
                .setSubject(username)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.RS512, privateKey)
                .setExpiration(new Date(exp))//设置过期时间
                .claim("role",roleList);
        return builder.compact();
    }

    public static Claims parseJwt(String token, PublicKey publicKey) {
        try {
            return Jwts.parser()
                    .setSigningKey(publicKey)
                    .parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            log.warn("[JjwtUtils][parseJwt]token已过期");
            throw new BizException("token已过期");
        }
    }

}
